package org.nobody.mallb2c.mallorder.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.nobody.mallb2c.mallorder.config.AlipayTemplate;
import org.nobody.mallb2c.mallorder.service.OrderService;
import org.nobody.mallb2c.mallorder.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-27-18:13
 */
@RestController
public class OrderPayedListener {
  @Autowired
  OrderService orderService;

  @Autowired
  AlipayTemplate alipayTemplate;

  @PostMapping("/payed/notify")
  public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
    System.out.println("handleAlipayed~~~~~~~~~");
//    Map<String, String[]> parameterMap = request.getParameterMap();
//    System.out.println("支付宝通知到位了,数据为: " + parameterMap);
//    for (String key : parameterMap.keySet()) {
//      String value = request.getParameter(key);
//      System.out.println("参数名: " + key + " ===> 参数值: " + value);
//    }

    //验签
    Map<String,String> params = new HashMap<String,String>();
    Map<String,String[]> requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      String[] values = (String[]) requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i]
          : valueStr + values[i] + ",";
      }
      //乱码解决，这段代码在出现乱码时使用
      //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
      params.put(name, valueStr);
    }
    boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(),alipayTemplate.getSign_type()); //调用SDK验证签名

    if(signVerified){
      System.out.println("签名验证成功...");
      String result = orderService.handlePayResult(vo);

      //只要我们收到了支付宝给我们异步的通知,告诉我们订单支付成功。
      //就应该返回success,这样支付宝就知道了,也就不再会通知了
      return result;
    }

    System.out.println("签名验证失败...");
    return "error";
  }
}
